/**
 * 
 */
package jvs.peer.xmpp;

import jvs.peer.io.ChannelManager;
import jvs.peer.io.File;
import jvs.peer.io.FileTransfer.Monitor;

import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;

/**
 * @author qiangli
 * 
 */
public class XmppShell extends Shell {

	private XMPPConnection conn;

	private FileTransferManager ftm;

	private XmppFileTransfer xft;

	public XmppShell(XMPPConnection conn) {
		this.conn = conn;
	}

	public void abort() throws Exception {
		xft.abort();
	}

	public void exit() {
		user = null;
	}

	public void init() {
		ftm = new FileTransferManager(conn);
		xft = new XmppFileTransfer(ftm);
	}

	public Monitor receive(File file) throws Exception {
		ensureAdmin();
		//
		String pid = user.getId();
		String desc = file.getPath();
		Monitor mon = xft.receive(pid, desc , file);
		return mon;
	}

	/**
	 * Admin can send (get) files to anyone
	 */
	public Monitor send(String peer, File file) throws Exception {
		String id = user.getId();
		String pid = StringUtils.parseBareAddress(peer);
		if (id.equals(pid) == false) {
			ensureAdmin();
		} else {
			checkAuth(file);
		}
		//
		String desc = file.getPath();
		Monitor mon = xft.send(peer, desc , file);
		return mon;
	}


	private void ensureAdmin() {
		// TODO Auto-generated method stub
	}

	private void checkAuth(File file) {
		// TODO Auto-generated method stub
	}

	/**
	 * only priviledged user (at least in one of the groups other than
	 * guest/public) can write each other
	 */
	public void write(String to, String message) throws Exception {
		ensureUser();
		//
		Message msg = new Message();
		msg.setThread(to);
		msg.setTo(to);
		msg.setType(Message.Type.normal);
		msg.setBody(message);
		conn.sendPacket(msg);
	}

	private void ensureUser() {
		// TODO Auto-generated method stub
	}

	public boolean ping(String peer) {
		return ChannelManager.getInstance().ping(peer);
	}
}
